package com.example.suanfademo;

public class BinarySearch {

    /*
    left 0  reight nums.length  mid left + right/2
    nums[mid]>target reight =mid-1
    nums[mid]<targat  left=mid+1
     */
    public int serch(int[] nums, int target) {
        int left = 0;
        int right = nums.length;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        BinarySearch binarySearch = new BinarySearch();
        int serch = binarySearch.serch(new int[]{22, 33, 44, 55, 66, 77, 88}, 55);
        System.out.println(serch);
    }

    /**
     * 二分查找
     *
     * @param nums   数组
     * @param target 目标值
     * @return 位置
     */
    public int binarySearch(int[] nums, int target) {
        // 超出范围
        if (target < nums[0] || target > nums[nums.length - 1]) {
            return -1;
        }
        // 判断边界
        if (target == nums[0]) {
            return 0;
        }
        if (target == nums[nums.length - 1]) {
            return nums.length - 1;
        }
        // 二分查找
        int left = 0, right = nums.length - 1;
        int index = 1;
        while (left < right - 1) {
            System.out.println("查找次数：" + index++);
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (target < nums[mid]) {
                right = mid;
            } else {
                left = mid;
            }
        }
        return -1;
    }

}
